/*
 * Licensed under the MIT License
 * 
 * Copyright (c) 2011 Kay Kreuning
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 * 
 * http://code.google.com/p/hyves-as3-sdk/
 */
package nl.hyves.api.utils
{
	import com.adobe.cairngorm.contract.Contract;
	import nl.hyves.api.core.IHyvesAPI;
	import nl.hyves.api.methods.Batch;
	import nl.hyves.api.net.HyvesRequest;
	import nl.hyves.api.net.HyvesResponse;
	import nl.hyves.api.net.IHyvesResponse;

	import flash.utils.Dictionary;

	public class BatchCall
	{
		private static const RESULTS_SPLITTER:RegExp = /\{\"\w+_result.+?(\}\}\})/g;
		private static const METHOD_EXTRACTOR:RegExp = /(?<=\{\")\w+(?=_result)/;
		private static const INFO_SPLITTER:RegExp = /,\"info\":.+?}/;
		private static const NAME_STRIPPER:RegExp = /(?<=_result\":).+?\}(?=\})/;
		
		private var service:IHyvesAPI;
		private var batch:Vector.<HyvesRequest>;
		private var callbackMap:Dictionary;

		public function get length():int
		{
			return batch.length;
		}

		public function BatchCall(service:IHyvesAPI)
		{
			Contract.precondition(service != null);
			
			this.service = service;
			batch = new Vector.<HyvesRequest>();
			callbackMap = new Dictionary();
			
			Contract.precondition(this.service != null);
			Contract.precondition(batch != null);
			Contract.precondition(callbackMap != null);
		}

		public function push(method:*, callback:Function, parameters:Object = null):void
		{
			Contract.precondition(method != null);
			Contract.precondition(callback != null);
			
			var request:HyvesRequest = new HyvesRequest(service, AuthUtil.buildParameters(method, parameters), callback);

			callbackMap[request.parameters['ha_method'].replace('.', '_')] = callback;
			
			Contract.postcondition(request != null);

			batch.push(request);
		}

		public function flush():void
		{
			service.call(Batch.process(batch), onBatchResponse);

			batch = null;
		}

		private function onBatchResponse(response:IHyvesResponse):void
		{
			// Split the results:
			var results:Array = response.raw.match(RESULTS_SPLITTER);

			for each (var result:String in results)
			{
				// Extract the method's name:
				var name:String = METHOD_EXTRACTOR.exec(result);

				// Strip off the info block:
				result = result.replace(INFO_SPLITTER, '');

				// Strip off name block:
				result = NAME_STRIPPER.exec(result);

				// Callback to the registered method:
				callbackMap[name](new HyvesResponse(result));
			}

			// Reset batch:
			batch = new Vector.<HyvesRequest>();
		}
	}
}